<?php
class User_Plugin_Core extends Zend_Controller_Plugin_Abstract
{
	public static function checkAuth()
	{
		$session = new Zend_Session_Namespace('Zend_Auth');
		//return ($session->user instanceof stdClass);
		return ($session->user != null);
	}
	
	public static function authenticate($username, $password)
	{
		$configApp = Zend_Registry::get('Config_Application');
		$appKey = $configApp['appsystem']['key'];
		
		$front = Zend_Controller_Front::getInstance();
		$dbAdapter = $front->getParam('bootstrap')->getResource('db');
		
		$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
		$authAdapter->setTableName('user_user')
					->setIdentityColumn('user_name')
					->setCredentialColumn('user_password');
		$authAdapter->setIdentity($username);
		$authAdapter->setCredential(md5($appKey . $password));

		$auth = Zend_Auth::getInstance();
		$result = $auth->authenticate($authAdapter);
		$flag = false;
		if ($result->isValid()) {
			$session = new Zend_Session_Namespace('Zend_Auth');
			$session->user = $authAdapter->getResultRowObject(null, array('password'));

			$auth->getStorage()->write($session->user);
			$flag = true;
		}
		
		return $flag;
	}
	
	public function logout()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
		$session = new Zend_Session_Namespace('Zend_Auth');
		$session->user = null;
    }
}